<template>
  <div class="container">
    <ButtonGroup :options="buttons" @click="handleButtonClick" />
    <p-table
      class="table-list-container"
      row-key="id"
      :custom-header-row="customHeaderRowMinxin"
      :columns="columns"
      bordered
      :scroll="{ x: '100%', y: 200 }"
      :pagination="false"
      :data-source="dataSource"
      @change="handleTableChange"
    />
    <DialogFiledFilter
      :visible.sync="visibleFiled"
      :fileds="fileds"
      @confirm="handleSelectFileds"
    />
  </div>
</template>

<script>
import mixinTable from '@/mixins/mixin-table.js';
import { createMonthArray } from '@/utils/time';
import DialogFiledFilter from '@/components/dialog/DialogFiledFilter.vue';

let index = 0;

export default {
  components: { DialogFiledFilter },
  mixins: [mixinTable],
  props: {
    parentId: {
      type: [String, Number],
      default: undefined,
    },
    timeRange: {
      type: Array,
      default: () => ['2021-01', '2021-05'],
    },
    dataSource: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      visibleFiled: false,
      filedsKeys: [],
    };
  },
  computed: {
    // totalData() {
    //   const totalKeys = Object.keys(this.dataSource[0]).filter((item) =>
    //     item.includes('month_')
    //   );
    //   console.log('totalKeys: ', totalKeys);
    //   const groups = this.dataSource.reduce((pre, cur) => {
    //     if (pre[cur.planSalesId]) {
    //       pre[cur.planSalesId].push(cur);
    //     } else {
    //       pre[cur.planSalesId] = [cur];
    //     }
    //     return pre;
    //   }, {});

    //   Object.keys(groups).forEach((group) => {
    //     groups[group] = groups[group].reduce(
    //       (pre, cur) => {
    //         totalKeys.forEach((key) => {
    //           console.log('cur[key]: ', cur[key], key);
    //           pre[key] = pre[key] || 0;
    //           console.log('pre[key]: ', pre[key], key);
    //           pre[key] += Number(cur[key]);
    //         });
    //         return pre;
    //       },
    //       { id: 'totalKey' }
    //     );
    //   });

    //   console.log('groups: ', groups);
    //   const data = Object.keys(groups).map((group) => {
    //     const items = this.dataSource.filter(
    //       (item) => item.planSalesId === Number(group)
    //     );
    //     items.push(groups[group]);
    //     console.log('groups.group: ', groups[group]);
    //     console.log('items: ', items);
    //     return items;
    //   });
    //   console.log('data: ', data.flat(1));
    //   return data.flat(1);
    // },
    ranges() {
      return createMonthArray(this.timeRange);
    },
    buttons() {
      return [
        // {
        //   key: 'show',
        //   label: '显示字段',
        // },
      ];
    },
    fileds() {
      return this.defaultCoulumns;
    },
    columns() {
      let columns = this.defaultCoulumns.filter((item) => !item.isHide);
      if (this.filedsKeys.length) {
        columns = columns.filter((item) => {
          return item.required || this.filedsKeys.includes(item.dataIndex);
        });
      }
      return columns;
    },
    defaultCoulumns() {
      return [
        {
          align: 'center',
          title: '序号',
          dataIndex: 'dataIndex',
          width: 60,
          customRender(t, r, index) {
            return parseInt(index) + 1;
          },
        },
        {
          align: 'center',
          title: '销售组',
          dataIndex: 'salesGroupName',
          ellipsis: true,
          width: 160,
          customRender: (value, row, index) => {
            const obj = { children: value, attrs: {} };
            if (index === 0) {
              obj.attrs.rowSpan = this.dataSource.length;
            }
            if (index > 0) {
              obj.attrs.rowSpan = 0;
            }
            return obj;
          },
        },
        {
          align: 'center',
          title: '客户简称',
          dataIndex: 'customerCode',
          ellipsis: true,
          width: 160,
        },
        {
          align: 'center',
          title: '客户项目',
          dataIndex: 'item',
          ellipsis: true,
          width: 160,
        },
        {
          align: 'center',
          title: '内部项目',
          dataIndex: 'innerItem',
          ellipsis: true,
          width: 160,
        },
        {
          align: 'center',
          title: '机种',
          dataIndex: 'modelNumber',
          ellipsis: true,
          width: 160,
        },
        {
          align: 'center',
          title: 'Model Name',
          dataIndex: 'modelName',
          ellipsis: true,
          width: 160,
        },
        {
          align: 'center',
          title: '应用别',
          dataIndex: 'application',
          ellipsis: true,
          width: 160,
        },
        {
          align: 'center',
          title: '形态',
          dataIndex: 'appearance',
          ellipsis: true,
          width: 160,
        },
        {
          align: 'center',
          title: '生产地',
          dataIndex: 'manufactureArea',
          ellipsis: true,
          width: 160,
        },
        {
          align: 'center',
          title: '模切比',
          dataIndex: 'modelCutRate',
          ellipsis: true,
          width: 160,
        },
        {
          align: 'center',
          title: '备注',
          dataIndex: 'remark',
          ellipsis: true,
          width: 160,
        },
        {
          align: 'center',
          title: '数量（小片Kpcs）',
          dataIndex: 'quantity',
          children: this.monthColumns('quantity'),
        },
        {
          align: 'center',
          title: '单价（人民币）',
          dataIndex: 'price',
          children: this.monthColumns('price'),
        },
        {
          align: 'center',
          title: '营收（人民币）',
          dataIndex: 'selfprice',
          children: this.monthColumns('selfprice'),
        },
        {
          align: 'center',
          title: '数量（大板Ksht）',
          dataIndex: 'selfnumber',
          children: this.monthColumns('selfnumber'),
        },
      ];
    },
  },
  methods: {
    handleSelectFileds(filedsKeys) {
      this.filedsKeys = filedsKeys;
    },
    createMonthObj() {
      return [...this.ranges, 'total'].reduce((pre, cur) => {
        pre[`pricemonth_${cur}`] = '';
        pre[`quantitymonth_${cur}`] = '';
        pre[`selfpricemonth_${cur}`] = '';
        pre[`selfnumbermonth_${cur}`] = '';
        return pre;
      }, {});
    },
    createDefaultItem() {
      return {
        id: index++,
        item: '',
        innerItem: '',
        customerCode: '',
        modelNumber: '',
        modelName: '',
        application: '',
        appearance: '',
        manufactureArea: '',
        modelCutRate: '',
        remark: '',
        price: '',
        quantity: '',
        ...this.createMonthObj(),
      };
    },
    totalAccount(type, record, index) {
      return Object.keys(record)
        .reduce((pre, cur) => {
          if (cur.startsWith(type)) {
            const n = Number(record[cur]) || 0;
            pre += n;
          }
          return pre;
        }, 0)
        .toFixed(2);
    },

    accountSelfPrice(row, dataIndex) {
      const date = dataIndex.split('_')[1];
      const price = Number(row[`pricemonth_${date}`]) || 0;
      const quantity = Number(row[`quantitymonth_${date}`]) || 0;
      const result = price * quantity;
      row[dataIndex] = result;
      return result;
    },

    selfnumber(row, dataIndex) {
      const date = dataIndex.split('_')[1];
      const modelCutRate = Number(row.modelCutRate) || 0;
      const quantity = Number(row[`quantitymonth_${date}`]) || 0;
      const result = Number((quantity / modelCutRate).toFixed(2)) || 0;
      row[dataIndex] = result;
      return result;
    },

    onInputChange(e, row, dataIndex) {
      // console.log('e, row, dataIndex: ', e, row, dataIndex);
      const value = e.target.value;
      row[dataIndex] = value;
    },

    monthColumns(key) {
      const price = (text, row, index, dataIndex) => {
        return <span>{text}</span>;
      };

      const selfprice = (text, row, index, dataIndex) => {
        return <span>{this.accountSelfPrice(row, dataIndex)}</span>;
      };

      const selfnumber = (text, row, index, dataIndex) => {
        return <span>{this.selfnumber(row, dataIndex)}</span>;
      };

      const renderMap = { price, quantity: price, selfprice, selfnumber };

      const list = this.ranges.map((item) => {
        const dataIndex = `${key}month_${item}`;
        return {
          align: 'center',
          title: item,
          width: 80,
          dataIndex,
          customRender: (text, row, index) =>
            renderMap[key](text, row, index, dataIndex),
        };
      });

      const totalKey = `${key}month_total`;
      const type = `${key}month`;
      list.push({
        align: 'center',
        title: '汇总',
        width: 80,
        dataIndex: totalKey,
        customRender: (text, row, index) => {
          return <span>{this.totalAccount(type, row)}</span>;
        },
      });
      return list;
    },
    handleInputChange(e, text, record, index, key) {
      console.log('text, record, index: ', e, text, record, index);
      this.dataSource[index][key] = e;
    },
    handleButtonClick(key) {
      const fn = `${key}Callback`;
      console.log('fn: ', fn);
      this[fn] && this[fn]();
    },
    deleteCallback() {
      const ids = this.rowSelectionMixin.selectedRowKeys;
      if (!ids.length) {
        this.$message.error('请先选择数据！');
        return;
      }
      this.$confirm(`该操作将删除 ${ids.length} 条数据，是否确认？`)
        .then(() => {
          ids.forEach((id) => {
            const index = this.dataSource.findIndex((item) => item.id === id);
            this.dataSource.splice(index, 1);
          });
          this.rowSelectionMixin.selectedRowKeys = [];
        })
        .catch(() => {
          // console.log('e: ', e);
        });
    },
    showCallback() {
      this.visibleFiled = true;
    },
    saveTemplateCallback() {
      console.log('saveTemplateCallback: ', this.saveTemplateCallback);
      this.$message.success('cheng');
    },
  },
};
</script>

<style lang="less" scoped>
.container {
  margin-bottom: 20px;
}
.table-list-container {
  margin-top: 10px;
}
</style>